using UnityEngine;
using System.Collections;
using System;
using System.IO;

public class GunRotationFollow : MonoBehaviour 
{

    public static float recoil = 0;
    public GameObject playerMovment;
    public float rotationSpeed = 3.0f;
    // The distance in the x-z plane to the target
    public float distance = 10.0f;
    // the height we want the camera to be above the target
    public float height = 5.0f;
    // How much we 
    public float heightDamping = 2.0f;
    public float rotationDamping = 3.0f;

    void Update()
    {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(playerMovment.transform.forward + new Vector3(0, recoil, 0)), Time.deltaTime * rotationSpeed);


        if (recoil > 0)
            recoil -= Time.deltaTime;
        else
            recoil = 0;
    }

    private void LateUpdate()
    {
        // Early out if we don't have a target
        if (!playerMovment)
            return;

        // Calculate the current rotation angles
        float wantedRotationAngle = playerMovment.transform.eulerAngles.y;
        float wantedHeight = playerMovment.transform.position.y + height;

        float currentRotationAngle = transform.eulerAngles.y;
        float currentHeight = transform.position.y;

        // Damp the rotation around the y-axis
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

        // Damp the height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // Convert the angle into a rotation
        Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position = playerMovment.transform.position;

        transform.position -= currentRotation * Vector3.forward * distance;

        // Set the height of the camera
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
        //transform.LookAt(target.transform.position);
    }
}
